﻿using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Tool;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace GYCTOAManagementSystemNewApi.Public
{
    /// <summary>
    /// JWT 管理类
    /// </summary>
    public class TokenManage
    {
        JWT jwt = new JWT();
        public TokenManage()
        {
            jwt.Secret = ConfigurationHelper.GetConfigValueByKey("Authentication:JwtBearer:secret");
            jwt.Issuer = ConfigurationHelper.GetConfigValueByKey("Authentication:JwtBearer:issuer");
            jwt.Audience = ConfigurationHelper.GetConfigValueByKey("Authentication:JwtBearer:audience");
            jwt.AccessExpiration = Convert.ToInt32(ConfigurationHelper.GetConfigValueByKey("Authentication:JwtBearer:accessExpiration"));
        }
        public string CreateToken(Users user,string Power)
        {
            //通过角色获取到权限所有项
            //var MenuNumber = string.Join(",", user.RoleId);
            string token = string.Empty;
            var claims = new[]
            {
                new Claim("Id", user.Id.ToString()),
                //new Claim("RoleId",MenuNumber),
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim("Power", Power),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
                new Claim("RoleIds", user.RoleId),

            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(jwt.Issuer, jwt.Audience, claims, expires: DateTime.Now.AddMinutes(jwt.AccessExpiration), signingCredentials: credentials);
            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            return token;
        }

        /// <summary>
        /// 获取解析数据
        ///    0    "Id", user.Id.ToString()    
        ///    1     UserName 
        ///    2     PowerNumber 
        ///    5     RoleIds
        /// </summary>
        /// <param name="Authorization">Authorization</param>
        /// <returns></returns>
        public static List<Claim> GetTokenValues(string Authorization)
        {
            if (!string.IsNullOrWhiteSpace(Authorization))
            {
                var jwtTokenHandler = new JwtSecurityTokenHandler();
                var aValidata = jwtTokenHandler.ReadJwtToken(Authorization);
                return aValidata.Claims.ToList();
            }
            throw new Exception("请重新登录系统");
                 
        }
    }
}
